//
//  EARoundMealController.m
//  WhatToEat
//
//  Created by 方力 on 15/8/1.
//  Copyright (c) 2015年 Mac. All rights reserved.
//



#import "EARoundMealController.h"
#import "EACollectionViewCell.h"
#import "EACircleLayout.h"
#import "EARectMealController.h"
#import "CDCircleOverlayView.h"
#import "EAMyTable.h"
#import "EAFoodDetailController.h"
#import "EAMealSetViewController1.h"
#import "EAChooseCategoryViewController.h"

@interface EARoundMealController ()<CDCircleDelegate, CDCircleDataSource,UICollectionViewDataSource,UICollectionViewDelegate,UITextFieldDelegate,UINavigationControllerDelegate>
@property(strong,nonatomic)UICollectionView * collectionView;
@property(strong,nonatomic)NSMutableArray * foods;
@property(strong,nonatomic)NSMutableArray * dataSouth;
@property(strong,nonatomic)UIButton * btn;

@property(strong,nonatomic)UILabel * numLabel;
@end

@implementation EARoundMealController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataSouth=[NSMutableArray array];
    
    self.selectFoods=[NSMutableArray array];
        [self updateUII];

    [self updateDataSouth];
    
    
    self.navigationController.delegate=self;
    

}

-(void)viewDidLayoutSubviews
{
    
    [super viewDidLayoutSubviews];
    self.navigationItem.title=@"自由选餐";
    
    //[self updateUI];
 

    
}






-(void)updateUII
{

    NSArray * array=@[@"肉类",@"蔬菜",@"水果",@"主食",@"点心"];


    for (int i=0; i<array.count; i++) {
        
        UIButton * bt=[[UIButton alloc] init];
        bt.top=10;
        bt.size=CGSizeMake(kUI_SCREEN_WIDTH/5, kUI_SCREEN_WIDTH/5);
        bt.left=i*kUI_SCREEN_WIDTH/5;

        
   

        [self.view addSubview:bt];

      
        [bt setImage:[UIImage imageNamed:[NSString stringWithFormat:@"zhushi%d",i+1]] forState:0];

        [bt setImage:[UIImage imageNamed:[NSString stringWithFormat:@"zhushi%d_s",i+1]] forState:UIControlStateSelected];
        
        UILabel * l=[[UILabel alloc] initWithFrame:CGRectMake(i*kUI_SCREEN_WIDTH/5, bt.bottom, kUI_SCREEN_WIDTH/5, 17)];
        [self.view addSubview:l];
        
        l.text=array[i];
        
        l.textAlignment=1;
        
        l.font=kFont(12);
        
        l.textColor=kTextLightColor;
        
        l.tag=i;
        
        bt.tag=i;
        
        
        [bt addTarget:self action:@selector(chooseAction:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i==0) {
            
            self.btn=bt;
            self.btn.selected=YES;
            
            
        
        }
        
        
    };
    
    
    UITextField * tf=[[UITextField alloc] initWithFrame:CGRectMake((kUI_SCREEN_WIDTH-200)/2, kUI_SCREEN_WIDTH/5+40, 150, 24)];
    
    tf.delegate=self;
    
    [self.view addSubview:tf];
    
    tf.placeholder=@"请输入菜名或菜的食材";
   // [tf setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
    [tf setValue:kFont(15) forKeyPath:@"_placeholderLabel.font"];
    tf.returnKeyType=UIReturnKeySearch;

    
    UIButton * searchBtn=[UIButton buttonWithType:0];
    
    [searchBtn setImage:[UIImage imageNamed:@"sousuo"] forState:0];
    
    searchBtn.userInteractionEnabled=YES;
    
    searchBtn.frame=CGRectMake(tf.right, tf.top-10, 44, 44);
    
    [self.view addSubview:searchBtn];
    
    
    searchBtn.rac_command=[[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    
        
                [tf resignFirstResponder];
        
                if (tf.text.length==0) {
        
        
        
        
                    [SVProgressHUD showImage:nil status:@"请输入食材名字"];
        
        
        
        
        
        
                    return [RACSignal empty];
                }
        
                [WebAPI webAPISignAddMd5tWithNote:@"meal/getMealByName" parm:@{
        
                                                                               @"name":tf.text
        
                                                                               } completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        
        
                                                                                   if ([kStr(responseObject[@"code"]) isEqualToString:@"1"]) {
                                                                                       
                                                                                       
                                                                                        self.dataSouth=responseObject[@"meal"];
                                                                                       
                                                                                       if (self.dataSouth.count>0) {
                                                                                           
                                                                                           
                                                                                       }
                                                                                       
                                                                                       [self.collectionView reloadData];
                                                                                       
                                                                                       
                                                                                       
                                                                                   }
                                                                                
        
                                                                                   
                                                                                   
                }];

        
        
        
        
        
        return [RACSignal empty];
    }];
    
    
    

    UIView * lineView=[[UIView alloc] initWithFrame:CGRectMake(tf.left-10, tf.bottom, tf.width+40, 1)];
    
    lineView .backgroundColor=kTingColor;
    
    [self.view addSubview:lineView];
    
    
    UIView * lineView1=[[UIView alloc] initWithFrame:CGRectMake(10, lineView.bottom+13, kUI_SCREEN_WIDTH-50, 1)];
    
    lineView1 .backgroundColor=[UIColor groupTableViewBackgroundColor];
    
    [self.view addSubview:lineView1];
    
    UICollectionViewFlowLayout *layot=[[UICollectionViewFlowLayout alloc] init];
    layot.itemSize=CGSizeMake(kUI_SCREEN_WIDTH/3-15, kUI_SCREEN_WIDTH/3-15);
    
    layot.sectionInset=UIEdgeInsetsMake(0, 10, 40, 10);
    
    self.collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, tf.bottom+30, kUI_SCREEN_WIDTH, self.view.height-tf.bottom-30-64) collectionViewLayout:layot];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"EACollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"EACollectionViewCell"];
    
    self.collectionView.dataSource=self;
    
    self.collectionView.delegate=self;

    self.collectionView.backgroundColor=kWhiteColor;
    
    [self.view addSubview:self.collectionView];

    
    UIView * bottomView=[[UIView alloc] initWithFrame:CGRectMake(0, kUI_SCREEN_HEIGHT-40-64, kUI_SCREEN_WIDTH, 40)];
    
    bottomView.backgroundColor=[UIColor blackColor];

    [self.view addSubview:bottomView];

    UILabel * nunLabel=[[UILabel alloc] initWithFrame:CGRectMake(14, 8, 24, 24)];
    
    nunLabel.text=@"0";
    
    nunLabel.textColor=[UIColor whiteColor];
    
    nunLabel.textAlignment=1;
    
    nunLabel.font=kFont(16);
    
    nunLabel.backgroundColor=bottomView.backgroundColor;
    
    nunLabel.layer.cornerRadius=CGRectGetMidX(nunLabel.bounds);
    
    nunLabel.clipsToBounds=YES;
    
    [bottomView addSubview:nunLabel];
    
    nunLabel.layer.borderWidth=1;
    
    nunLabel.layer.borderColor=[UIColor whiteColor].CGColor;

    self.numLabel=nunLabel;
    
    
    UIButton * myTableBtn=[[UIButton alloc] initWithFrame:CGRectMake(kUI_SCREEN_WIDTH-90, 5, 80, 30)];
    
    myTableBtn.backgroundColor=kTingColor;
    
    myTableBtn.titleLabel.font=kFont(14);
    
    myTableBtn.layer.cornerRadius=5;
    
    myTableBtn.clipsToBounds=YES;
    
    [myTableBtn setTitle:@"加入餐桌" forState:0];
    
    [myTableBtn addTarget:self action:@selector(toMyTableView) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView addSubview:myTableBtn];
    

    
    [[self.selectFoods rac_signalForSelector:@selector(addObject:)] subscribeNext:^(id x) {
        
        
        
        [SVProgressHUD showImage:nil status:@"加入餐桌成功"];
        self.numLabel.text=[NSString stringWithFormat:@"%lu",self.selectFoods.count];
        
        
    }];
    
}




#pragma mark-----

-(void)toMyTableView
{
    
//        self.tabBarController.selectedIndex=1;
//
//    UINavigationController * nVC=self.tabBarController.viewControllers[1];
//    
//    
//    EAMyTable * myVC=(EAMyTable *)nVC.visibleViewController;
//    
//    
//
//    myVC.foods=self.selectFoods;
//  var sd=EAMealSetingViewController();
    
    if (self.selectFoods&&self.selectFoods.count==0) {
        
        [SVProgressHUD showImage:nil status:@"先增加食物"];
        
        
        return;
        
        
    }
    
    
    
    
    EAMealSetViewController1 *sw=[[EAMealSetViewController1 alloc] init];
    

    sw.aty_level=self.aty_level;
    
    sw.mealtype=self.mealtype;

    
    
    sw.dataSouth=self.selectFoods;
    
    NSLog(@"%@",self.selectFoods);
    
    self.hidesBottomBarWhenPushed=NO;
    [self.navigationController pushViewController:sw animated:YES];

    self.hidesBottomBarWhenPushed=YES;

   

// self.navigationController.pushViewController(EAMealSetingViewController (),animated:true)




}

-(void)chooseAction:(UIButton *)btn
{

    btn.selected=YES;
    
    for (UIView * v in self.view.subviews) {
        
        if ([v isKindOfClass:[UIButton class]]) {
            
            
            if ([btn isEqual:v]) {
                
                self.btn=btn;
                [self updateDataSouth ];
            }else
            {
            
                UIButton * bt=(UIButton *)v;
                
                
                bt.selected=NO;
                
            
            }
            
            
        
            
            
            
        }
        
        if ([v isKindOfClass:[UILabel class]]) {
            
            UILabel * l=(UILabel *)v;
            
            if (l.tag==btn.tag) {
                
                l.font=kFont(17);
            }else
            {
            
                l.font=kFont(14);
            
            }
            
            
        
            
            
            
            
            
        }
        
        
        
        
        
        
        
        
    }
    
    





}



-(void)updateDataSouth
{
    
    NSString * categoryString;
    
    switch (self.btn.tag) {
        case 0:
            categoryString=@"2";
            break;
            
        case 1:
            categoryString=@"1";
            break;
        case 2:
            categoryString=@"4";
            break;
        case 3:
            categoryString=@"3";
            break;
        case 4:
            categoryString=@"5";
            break;
        default:
            break;
    }
    

    
    
    
    
    [WebAPI webAPISignAddMd5tWithNote:@"user/getFood" parm:@{
                                                             @"category":categoryString
                                                             
                                                             } completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
                                                                 
                                                                 
                                                                 
                                                                 
                                                                 self.dataSouth=responseObject[@"food"];
                                                                 [self.collectionView reloadData];
    }];





}



-(void)toRectVC
{
    
    EARectMealController * rvc=[[EARectMealController alloc] init];
    
    
    
    [self.navigationController pushViewController:rvc animated:YES];
    
    
    
    
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    if ([string isEqualToString:@"\n"]) {
        
        [textField resignFirstResponder];
        
        if (textField.text.length==0) {
            
            
            
            
            [SVProgressHUD showImage:nil status:@"请输入食材名字"];
            
            
            
            
            
            
            return [RACSignal empty];
        }
        
        [WebAPI webAPISignAddMd5tWithNote:@"meal/getMealByName" parm:@{
                                                                       
                                                                       @"name":textField.text
                                                                       
                                                                       } completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
                                                                           
                                                                           
                                                                           if ([kStr(responseObject[@"code"]) isEqualToString:@"1"]) {
                                                                               
                                                                               
                                                                               self.dataSouth=responseObject[@"meal"];
                                                                               
                                                                               if (self.dataSouth.count>0) {
                                                                                   
                                                                                   
                                                                               }
                                                                               
                                                                               [self.collectionView reloadData];
                                                                               
                                                                               
                                                                               
                                                                           }
                                                                           
                                                                           
                                                                           
                                                                           
                                                                       }];
        
        
        return NO;
    }



    return YES;
}



- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
    
    return self.dataSouth.count;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{
    
    EACollectionViewCell * cell=[collectionView  dequeueReusableCellWithReuseIdentifier:@"EACollectionViewCell" forIndexPath:indexPath];
    
    NSDictionary * d=self.dataSouth[indexPath.row];
    
    
    cell.nameLabel.text=d[@"name"];
    
    [cell.headImageView setImageWithURL:[NSURL URLWithString:d[@"img"]]];
    
    cell.backgroundColor=kWhiteColor;
    
    
    cell.kTapAction=^(UITapGestureRecognizer * tap)
    {
        
        NSLog(@"%@",tap);
        CGPoint  p=[tap locationInView:cell];
        
        if (CGRectContainsPoint(cell.nameLabel.frame, p)) {
            
            EAFoodDetailController * fDVC=[[EAFoodDetailController alloc] init];
            
            
            fDVC.foodDict=d;
            
            fDVC.selectFoods=self.selectFoods;
      
            
            [self.navigationController pushViewController:fDVC animated:YES];
            
        
           self.hidesBottomBarWhenPushed=YES;
        }else
        {
        
//            NSDictionary * d=self.dataSouth[indexPath.row];
            
            NSDictionary * d=[self.dataSouth[indexPath.row] mutableCopy];
            
            [d setValue:@"1" forKey:@"num"];
            
            if ([self.selectFoods containsObject:d]) {
                
                [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"已经选择%@",d[@"name"]]];
                
                return;
            }
            
            [self.selectFoods addObject:d];

        }
        
        
        
        
    };
    
    
    return cell;
    
    
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    
    
    
    
}
-(void)dealloc
{
    
    
    NSLog(@"销毁类-----%@",self);
    
    
}







- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{





}



@end
